#include "common.h"
#include "voicectl.h"

#define LEDALL	"/sys/kernel/gec_ctrl/led_all"	
//#define REC_CMD  "./arecord -d4 -c1 -r16000 -traw -fS16_LE cmd.pcm"
#define REC_CMD  "arecord -d3 -c1 -r16000 -traw -fS16_LE cmd.pcm"
#define PCM_FILE "./cmd.pcm"


char* MP3[] = { "./1.mp3","./2.mp3",
		"./3.mp3" ,"./4.mp3"  };
/* -d：录音时长（duration）
-c：音轨（channels）
-r：采样频率（rate）
-t：封装格式（type）
-f：量化位数（format） */

void catch (int sig)
{
	if (sig == SIGPIPE)
	{
		printf("killed by SIGPIPE\n");
		exit(0);
	}
}


int led_flag = 1;
int mp3_flag1 = 0;
int door_flag = 1;
int music_count = 0;
char cmd[30] = { 0 };

int voicectl(char *ip)
{
	
	signal(SIGPIPE, catch);
	// 初始化TCP客户端套接字，用于连接到语音识别服务器(即ubuntu)
	int sockfd_tcp = init_tcp_socket(ip);
	// 初始化本地UDP套接字
	int sockfd_udp = init_udp_socket();

	int id_num = -1; // 识别后的指令id
	while (1)
	{
		// 1，调用arecord来录一段音频
		printf("please to start REC in 3s...\n");

		// 在程序中执行一条命令  “录音的命令”
		system(REC_CMD);

		// 2，将录制好的PCM音频发送给语音识别引擎
		send_pcm(sockfd_tcp, PCM_FILE);

		// 3，等待对方回送识别结果（字符串ID）
		xmlChar* id = wait4id(sockfd_tcp);
		if (id == NULL)
		{
			continue;
		}
		id_num = atoi((char*)id);

		if (id_num == 1) //开门
		{
			if (led_flag == 1)
			{
				bmp_display("./bmp/7.bmp", 0, 0);  //开门关灯
				door_flag = -1;
			}
			else
			{
				bmp_display("./bmp/4.bmp", 0, 0);  //开门开灯
				door_flag = -1;
			}
		}
		if (id_num == 2) //开灯
		{
			if (door_flag == 1)
			{
				bmp_display("./bmp/6.bmp", 0, 0);  //关门开灯
				led_flag = -1;
			}
			else
			{
				bmp_display("./bmp/4.bmp", 0, 0);  //开门开灯
				led_flag = -1;
			}
			led_ctl(LEDALL, 1);
		}
		if (id_num == 3) //播放音乐
		{
			system("madplay ./1.mp3 -r &");
			mp3_flag1 = 1;
		}
		if (id_num == 4)//关门
		{
			if (led_flag == 1)
			{
				bmp_display("./bmp/2.bmp", 0, 0);
				door_flag = 1;
			}
			else
			{
				bmp_display("./bmp/6.bmp", 0, 0);
				door_flag = 1;
			}
		}
		if (id_num == 5) //关灯
		{
			if (door_flag == 1)
			{
				bmp_display("./bmp/2.bmp", 0, 0);
				led_flag = 1;
			}
			else
			{
				bmp_display("./bmp/8.bmp", 0, 0);
				led_flag = 1;
			}
			led_ctl(LEDALL, 0);

		}

		if (id_num == 6)//关闭音乐
		{
			system("killall -9 madplay ");
			mp3_flag1 = 0;
		}

		if (id_num == 8)//下一首
		{
			if (mp3_flag1)
			{
				system("killall -9 madplay ");
			}
			music_count--;
			if (music_count == -1)
			{
				music_count = 3;
			}
			sprintf(cmd, "madplay %s -r &", MP3[music_count]);
			system(cmd);
			mp3_flag1 = 1;
		}

		if (id_num == 7)//上一首
		{
			if (mp3_flag1)
			{
				system("killall -9 madplay ");
			}
			music_count++;
			if (music_count == 4)
			{
				music_count = 0;
			}
			sprintf(cmd, "madplay %s -r &", MP3[music_count]);
			system(cmd);
			mp3_flag1 = 1;
		}

		if (id_num == 999)
		{
			if (mp3_flag1)
			{
				system("killall -9 madplay ");
			}
			printf("bye-bye!\n");
			return -1;
		}
		printf("recv id: %d \n", id_num);
		// udp发送数据给接收端, 接收端收到数据id后，再决定执行什么功能
		send_id(sockfd_udp, id_num);
		
	}

	return 0;
}
